const koa = require('koa')
const router = require('koa-router')()
const koaBody = require('koa-body')();
const views = require('koa-views');
var Q = require('q')

var ClockIn = require('./clock-in.js')
const Stuff = require('./stuff.js')

const app = koa()

router.get('/', index)
router.post('/', koaBody, handleClockInOff)




// Must be used before any router is used
app.use(views(__dirname + '/views', {
  map: {
    html: 'jade'
  },
  default: 'jade'
}));

app.use(router.routes()).use(router.allowedMethods())
app.use(require('koa-static')(__dirname + '/public'))

function *index(next) {
  yield this.render('index')
}

function *handleClockInOff(next) {

  var id = this.request.body.id
  console.log(id)
  var stuff = Stuff.getStuff(id)

  var result = yield function *() {
    var q = Q.defer()
    ClockIn.clockIn(stuff, (text)=> {
       q.resolve(text)
    })
    return q.promise
  }

  this.body = result

  // yield next
}


app.listen(8080)
console.log('Day Clock Start')